#!/usr/bin/env python3
"""
Flask博客系统部署脚本
支持Docker和传统部署方式
"""

import os
import sys
import subprocess
import argparse
from pathlib import Path

def check_docker():
    """检查Docker是否安装"""
    try:
        subprocess.run(['docker', '--version'], check=True, capture_output=True)
        subprocess.run(['docker-compose', '--version'], check=True, capture_output=True)
        print("✅ Docker 和 Docker Compose 已安装")
        return True
    except (subprocess.CalledProcessError, FileNotFoundError):
        print("❌ Docker 或 Docker Compose 未安装")
        print("请访问 https://docs.docker.com/get-docker/ 安装Docker")
        return False

def docker_deploy():
    """Docker部署"""
    print("🐳 开始Docker部署...")
    
    if not check_docker():
        return False
    
    try:
        # 构建镜像
        print("📦 构建Docker镜像...")
        subprocess.run(['docker-compose', 'build'], check=True)
        
        # 启动服务
        print("🚀 启动服务...")
        subprocess.run(['docker-compose', 'up', '-d'], check=True)
        
        print("✅ Docker部署完成!")
        print("📍 访问地址: http://localhost")
        print("🔧 管理后台: http://localhost/admin")
        print("👤 默认账户: admin / admin123")
        print()
        print("📋 常用命令:")
        print("  查看日志: docker-compose logs -f")
        print("  停止服务: docker-compose down")
        print("  重启服务: docker-compose restart")
        
        return True
    except subprocess.CalledProcessError as e:
        print(f"❌ Docker部署失败: {e}")
        return False

def traditional_deploy():
    """传统部署"""
    print("🔧 开始传统部署...")
    
    # 检查Python版本
    if sys.version_info < (3, 8):
        print("❌ 需要 Python 3.8 或更高版本")
        return False
    
    # 安装依赖
    print("📦 安装依赖...")
    try:
        subprocess.run([sys.executable, '-m', 'pip', 'install', '-r', 'requirements.txt'], check=True)
    except subprocess.CalledProcessError as e:
        print(f"❌ 依赖安装失败: {e}")
        return False
    
    # 创建必要目录
    Path('app/static/uploads').mkdir(parents=True, exist_ok=True)
    
    # 设置环境变量
    os.environ.setdefault('FLASK_ENV', 'production')
    os.environ.setdefault('SECRET_KEY', 'your-secret-key-change-in-production')
    
    print("✅ 传统部署准备完成!")
    print("🚀 启动命令: python run.py")
    print("📍 访问地址: http://localhost:5000")
    print("🔧 管理后台: http://localhost:5000/admin")
    
    return True

def production_deploy():
    """生产环境部署"""
    print("🏭 开始生产环境部署...")
    
    # 检查必要文件
    required_files = ['Dockerfile', 'docker-compose.yml', 'nginx.conf']
    for file in required_files:
        if not Path(file).exists():
            print(f"❌ 缺少必要文件: {file}")
            return False
    
    # 创建生产环境配置
    env_content = """# 生产环境配置
FLASK_ENV=production
SECRET_KEY=your-very-long-random-secret-key-change-this
DATABASE_URL=postgresql://bloguser:blogpass@db:5432/blogdb
ADMIN_EMAIL=admin@yourdomain.com
ADMIN_PASSWORD=your-strong-password

# 邮件配置（可选）
# MAIL_SERVER=smtp.gmail.com
# MAIL_PORT=587
# MAIL_USE_TLS=True
# MAIL_USERNAME=your-email@gmail.com
# MAIL_PASSWORD=your-app-password
"""
    
    with open('.env.production', 'w') as f:
        f.write(env_content)
    
    print("📝 生产环境配置文件已创建: .env.production")
    print("⚠️  请修改 .env.production 中的配置信息")
    print()
    print("🚀 部署命令:")
    print("  docker-compose -f docker-compose.yml -f docker-compose.prod.yml up -d")
    print()
    print("🔒 安全建议:")
    print("  1. 修改默认密码和密钥")
    print("  2. 配置SSL证书")
    print("  3. 设置防火墙规则")
    print("  4. 定期备份数据")
    
    return True

def show_status():
    """显示服务状态"""
    print("📊 服务状态:")
    try:
        subprocess.run(['docker-compose', 'ps'], check=True)
    except subprocess.CalledProcessError:
        print("❌ 无法获取服务状态")
    except FileNotFoundError:
        print("❌ Docker Compose 未安装")

def show_logs():
    """显示日志"""
    print("📋 服务日志:")
    try:
        subprocess.run(['docker-compose', 'logs', '--tail=50'], check=True)
    except subprocess.CalledProcessError:
        print("❌ 无法获取日志")
    except FileNotFoundError:
        print("❌ Docker Compose 未安装")

def main():
    """主函数"""
    parser = argparse.ArgumentParser(description='Flask博客系统部署脚本')
    parser.add_argument('command', choices=['docker', 'traditional', 'production', 'status', 'logs'], 
                       help='部署命令')
    
    args = parser.parse_args()
    
    print("🎉 Flask博客系统部署工具")
    print("=" * 50)
    
    if args.command == 'docker':
        docker_deploy()
    elif args.command == 'traditional':
        traditional_deploy()
    elif args.command == 'production':
        production_deploy()
    elif args.command == 'status':
        show_status()
    elif args.command == 'logs':
        show_logs()

if __name__ == '__main__':
    if len(sys.argv) == 1:
        print("使用方法:")
        print("  python deploy.py docker        # Docker部署")
        print("  python deploy.py traditional   # 传统部署")
        print("  python deploy.py production    # 生产环境部署")
        print("  python deploy.py status        # 查看状态")
        print("  python deploy.py logs          # 查看日志")
        sys.exit(1)
    
    main()

